// 通用工具类
const config = require('../config/config.js')

class Utils {
  // 格式化价格
  formatPrice(price) {
    if (price === null || price === undefined) return '0.00'
    return parseFloat(price).toFixed(2)
  }

  // 格式化时间
  formatTime(timestamp, format = 'YYYY-MM-DD HH:mm:ss') {
    if (!timestamp) return ''
    
    const date = new Date(timestamp)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    const second = String(date.getSeconds()).padStart(2, '0')

    return format
      .replace('YYYY', year)
      .replace('MM', month)
      .replace('DD', day)
      .replace('HH', hour)
      .replace('mm', minute)
      .replace('ss', second)
  }

  // 格式化相对时间
  formatRelativeTime(timestamp) {
    if (!timestamp) return ''
    
    const now = Date.now()
    const diff = now - new Date(timestamp).getTime()
    
    if (diff < 60000) { // 1分钟内
      return '刚刚'
    } else if (diff < 3600000) { // 1小时内
      return `${Math.floor(diff / 60000)}分钟前`
    } else if (diff < 86400000) { // 1天内
      return `${Math.floor(diff / 3600000)}小时前`
    } else if (diff < 2592000000) { // 30天内
      return `${Math.floor(diff / 86400000)}天前`
    } else {
      return this.formatTime(timestamp, 'YYYY-MM-DD')
    }
  }

  // 防抖函数
  debounce(func, wait) {
    let timeout
    return function executedFunction(...args) {
      const later = () => {
        clearTimeout(timeout)
        func(...args)
      }
      clearTimeout(timeout)
      timeout = setTimeout(later, wait)
    }
  }

  // 节流函数
  throttle(func, limit) {
    let inThrottle
    return function executedFunction(...args) {
      if (!inThrottle) {
        func.apply(this, args)
        inThrottle = true
        setTimeout(() => inThrottle = false, limit)
      }
    }
  }

  // 深拷贝
  deepClone(obj) {
    if (obj === null || typeof obj !== 'object') return obj
    if (obj instanceof Date) return new Date(obj.getTime())
    if (obj instanceof Array) return obj.map(item => this.deepClone(item))
    if (typeof obj === 'object') {
      const clonedObj = {}
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          clonedObj[key] = this.deepClone(obj[key])
        }
      }
      return clonedObj
    }
  }

  // 生成唯一ID
  generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2)
  }

  // 验证手机号
  validatePhone(phone) {
    const phoneReg = /^1[3-9]\d{9}$/
    return phoneReg.test(phone)
  }

  // 验证邮箱
  validateEmail(email) {
    const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return emailReg.test(email)
  }

  // 获取图片完整URL
  getImageUrl(path) {
    if (!path) return config.defaultImage
    if (path.startsWith('http')) return path
    return config.ossUrl + '/' + path
  }

  // 获取头像完整URL
  getAvatarUrl(path) {
    if (!path) return config.defaultAvatar
    if (path.startsWith('http')) return path
    return config.ossUrl + '/' + path
  }

  // 显示Toast
  showToast(title, icon = 'success', duration = 2000) {
    wx.showToast({
      title,
      icon: icon === 'success' ? 'success' : 'none',
      duration
    })
  }

  // 显示加载中
  showLoading(title = '加载中...') {
    wx.showLoading({
      title,
      mask: true
    })
  }

  // 隐藏加载中
  hideLoading() {
    wx.hideLoading()
  }

  // 显示确认对话框
  showConfirm(content, title = '提示') {
    return new Promise((resolve) => {
      wx.showModal({
        title,
        content,
        success: (res) => {
          resolve(res.confirm)
        }
      })
    })
  }

  // 显示操作菜单
  showActionSheet(itemList) {
    return new Promise((resolve, reject) => {
      wx.showActionSheet({
        itemList,
        success: (res) => {
          resolve(res.tapIndex)
        },
        fail: reject
      })
    })
  }

  // 复制到剪贴板
  copyToClipboard(data) {
    return new Promise((resolve, reject) => {
      wx.setClipboardData({
        data,
        success: () => {
          this.showToast('已复制到剪贴板')
          resolve()
        },
        fail: reject
      })
    })
  }

  // 拨打电话
  makePhoneCall(phoneNumber) {
    wx.makePhoneCall({
      phoneNumber,
      fail: () => {
        this.showToast('拨打失败', 'none')
      }
    })
  }

  // 预览图片
  previewImage(urls, current = 0) {
    wx.previewImage({
      urls,
      current: typeof current === 'number' ? urls[current] : current
    })
  }

  // 选择图片
  chooseImage(count = 1, sizeType = ['compressed'], sourceType = ['album', 'camera']) {
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count,
        sizeType,
        sourceType,
        success: resolve,
        fail: reject
      })
    })
  }

  // 获取位置信息
  getLocation(type = 'gcj02') {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type,
        success: resolve,
        fail: reject
      })
    })
  }

  // 打开地图
  openLocation(latitude, longitude, name = '', address = '') {
    wx.openLocation({
      latitude,
      longitude,
      name,
      address,
      scale: 18
    })
  }

  // 获取系统信息
  getSystemInfo() {
    return new Promise((resolve, reject) => {
      wx.getSystemInfo({
        success: resolve,
        fail: reject
      })
    })
  }

  // 设置导航栏标题
  setNavigationBarTitle(title) {
    wx.setNavigationBarTitle({
      title
    })
  }

  // 页面跳转
  navigateTo(url) {
    wx.navigateTo({
      url,
      fail: () => {
        this.showToast('页面跳转失败', 'none')
      }
    })
  }

  // 页面重定向
  redirectTo(url) {
    wx.redirectTo({
      url,
      fail: () => {
        this.showToast('页面跳转失败', 'none')
      }
    })
  }

  // 切换Tab页面
  switchTab(url) {
    wx.switchTab({
      url,
      fail: () => {
        this.showToast('页面跳转失败', 'none')
      }
    })
  }

  // 返回上一页
  navigateBack(delta = 1) {
    wx.navigateBack({
      delta
    })
  }

  // 获取订单状态信息
  getOrderStatusInfo(status) {
    return config.orderStatus[status] || { text: '未知状态', color: '#999' }
  }

  // 获取支付方式信息
  getPaymentMethodInfo(method) {
    return config.paymentMethods[method] || { text: '未知支付方式', icon: '' }
  }

  // 获取配送方式信息
  getDeliveryMethodInfo(method) {
    return config.deliveryMethods[method] || { text: '未知配送方式', fee: 0, desc: '' }
  }

  // 计算距离
  calculateDistance(lat1, lng1, lat2, lng2) {
    const radLat1 = lat1 * Math.PI / 180.0
    const radLat2 = lat2 * Math.PI / 180.0
    const a = radLat1 - radLat2
    const b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0
    let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
      Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
    s = s * 6378.137
    s = Math.round(s * 10000) / 10000
    return s
  }

  // 格式化距离
  formatDistance(distance) {
    if (distance < 1) {
      return `${Math.round(distance * 1000)}m`
    } else {
      return `${distance.toFixed(1)}km`
    }
  }

  // 数组去重
  uniqueArray(arr, key) {
    if (!key) {
      return [...new Set(arr)]
    }
    const seen = new Set()
    return arr.filter(item => {
      const val = item[key]
      if (seen.has(val)) {
        return false
      }
      seen.add(val)
      return true
    })
  }

  // 数组分组
  groupBy(arr, key) {
    return arr.reduce((groups, item) => {
      const group = item[key]
      groups[group] = groups[group] || []
      groups[group].push(item)
      return groups
    }, {})
  }

  // 检查是否为空
  isEmpty(value) {
    return value === null || value === undefined || value === '' ||
           (Array.isArray(value) && value.length === 0) ||
           (typeof value === 'object' && Object.keys(value).length === 0)
  }

  // URL参数解析
  parseQuery(url) {
    const query = {}
    const queryString = url.split('?')[1]
    if (queryString) {
      queryString.split('&').forEach(param => {
        const [key, value] = param.split('=')
        query[decodeURIComponent(key)] = decodeURIComponent(value || '')
      })
    }
    return query
  }

  // 构建URL参数
  buildQuery(params) {
    const query = Object.keys(params)
      .filter(key => params[key] !== null && params[key] !== undefined && params[key] !== '')
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&')
    return query
  }
}

// 创建工具实例
const utils = new Utils()

module.exports = utils